﻿using BLL;
using DAL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.选择窗体;

namespace 纺织贸易管理系统.新增窗体
{
    public partial class 客供出仓单 : Form
    {
        public FormUseful useful { get; set; } = FormUseful.新增;
        public List<danjumingxitable> danjumingxitables = new List<danjumingxitable>();     
        public DanjuTable danju = new DanjuTable();
        public List<StockTable> stockTables = new List<StockTable>();
        private List<JuanHaoTable> juanList = new List<JuanHaoTable>();
        private int rowindex;

        public 客供出仓单()
        {
            InitializeComponent();
            InitGrid();
        }
        private void InitGrid()
        {
            CreateGrid.Create(this.Name, gridView1);
            CreateGrid.Create(this.Name, gridView2);
            cmb领用人.DataSource = YuanGongTableService.GetYuanGongTablelst().Select(x=>x.Xingming).ToList();
            cmbMadanYangshi.Text = SettingService.GetSetting(new Setting() { formname = this.Name, settingname = "码单样式", settingValue = "" }).settingValue;
            try
            {
                if (gridView1.Columns["Bianhao"] != null)
                {
                    gridView1.Columns["Bianhao"].ColumnEdit = ButtonEdit1;
                }
                if (gridView1.Columns["pingming"] != null)
                {
                    gridView1.Columns["pingming"].ColumnEdit = ButtonEdit1;
                }
                if (gridView1.Columns["OrderNum"] != null)
                {
                    gridView1.Columns["OrderNum"].ColumnEdit = ButtonEdit1;
                }
                if (gridView1.Columns["ganghao"] != null)
                {
                    gridView1.Columns["ganghao"].ColumnEdit = ButtonEdit1;
                }
                if (gridView1.Columns["danwei"] != null)
                {
                    gridView1.Columns["danwei"].ColumnEdit = cmddanwei;
                }
                gridView1.Columns["hanshuiheji"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gridView1.Columns["hanshuiheji"].SummaryItem.FieldName = "hanshuiheji";
                gridView1.Columns["hanshuiheji"].SummaryItem.DisplayFormat = "{0:0.##}";
                gridView1.Columns["chengpingmishu"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gridView1.Columns["chengpingmishu"].SummaryItem.FieldName = "chengpingmishu";
                gridView1.Columns["chengpingmishu"].SummaryItem.DisplayFormat = "{0:0.##}";
                gridView1.Columns["chengpingjuanshu"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gridView1.Columns["chengpingjuanshu"].SummaryItem.FieldName = "chengpingjuanshu";
                gridView1.Columns["chengpingjuanshu"].SummaryItem.DisplayFormat = "{0:0.##}";
                cmbMadanYangshi.Text = SettingService.GetSetting(new Setting() { formname = "销售发货单", settingname = "码单样式", settingValue = "" }).settingValue;
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox("生成表格的时候发送了错误！需要重新配置列:" + ex.Message);
                配置列ToolStripMenuItem_Click(null, null);
            }
        }
        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = new danjumingxitable() };
            fm.ShowDialog();
        }
        private void txtkehu_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 客户选择() { linkman=new LXR() { MC="",ZJC="" } };
            fm.ShowDialog();
            danju.ksbh = fm.linkman.BH;
            danju.ksmc = fm.linkman.MC;
            txtkehu.Text = danju.ksmc;
        }
        private void txtckmc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(cmbcunfang.Text=="仓库")
            {
                var fm = new 仓库选择();
                fm.ShowDialog();
                txtckmc.Text = fm.stock.mingcheng;
            }
            else
            {
               var fm = new 供货商选择() { linkman=new LXR() { ZJC=txtckmc.Text } };
                fm.ShowDialog();
                txtckmc.Text = fm.linkman.MC;
            }
        }

        private void ButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(txtckmc.Text =="")
            {
                MessageBox.Show("请先选择仓库名称","错误",MessageBoxButtons.OK );
                return;
            }
            var fm = new 库存选择() { StockName=txtckmc.Text };
            fm.ShowDialog();
            SelectHelper.StockConverToDanjumingxi(gridView1, fm.pingzhong , danjumingxitables, txtdanhao.Text, dateEdit1.DateTime, DanjuLeiXing.客供出仓单);
            txtbeizhu.Text = danjumingxitables[0].houzhengli;
            gridControl1.RefreshDataSource();
            gridView1.CloseEditor();
            加载卷();
        }
        private void 加载卷()
        {
            juanList.Clear();
            foreach (var d in danjumingxitables.Where (x=>!string.IsNullOrWhiteSpace ( x.pingming)) )
            {
                juanList.AddRange(JuanHaoTableService.GetJuanHaoTablelst(x => x.ReceiptNo == d.rkdh&&x.CustomerName==d.CustomName && x.yanse == d.yanse  && x.GangHao == d.ganghao && x.Ckmc == txtckmc.Text && x.state==0));
            }
            juanList = juanList.OrderBy(x => x.GangHao).ToList();
            gridControl2.DataSource=juanList ;
        }
        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.DeleteRow(gridView1.FocusedRowHandle);
        }

        private void 添加行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            danjumingxitables.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = Convert.ToDateTime(dateEdit1.Text) });
        }

        private void 复制行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rowindex = gridView1.FocusedRowHandle;
        }

        private void 粘贴行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyRow.Copy<danjumingxitable>(danjumingxitables, rowindex, gridView1, gridView1.FocusedRowHandle, this);
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //try
            //{
            //    danjumingxitables[gridView1.FocusedRowHandle].hanshuiheji = danjumingxitables[gridView1.FocusedRowHandle].hanshuidanjia * danjumingxitables[gridView1.FocusedRowHandle].chengpingmishu;
            //    gridControl1.RefreshDataSource();
            //}
            //catch 
            //{
            //    MessageBox.Show("请输入数字。计算错误");
            //}
        }
        private void InitDanju()
        {
            danju.bz = txtbeizhu.Text;
            danju.StockName = cmbcunfang.Text;
            danju.ckmc = txtckmc.Text;
            danju.dh = txtdanhao.Text;
            danju.djlx = DanjuLeiXing.客供出仓单;
            danju.rq = dateEdit1.DateTime;
            danju.shouhuodizhi = txtckmc.Text;
            //danju.Qiankuan = cmbqiankuan.Text;
            //danju.Hanshui = comhanshui.Text;
            danju.je = danjumingxitables.Sum(x => x.hanshuiheji);
            danju.totaljuanshu = danjumingxitables.Sum(x => x.chengpingjuanshu);
            danju.TotalMishu = danjumingxitables.Sum(x => x.chengpingmishu);
            danju.zhuangtai = "未审核";
            danju.own = Tools.CurrentUser.user.YHBH;
            danju.SaleMan = cmb领用人.Text;
        }
        private List<JuanHaoTable> CreatJuanhao()
        {
            var juan = new List<JuanHaoTable>();
            foreach (var j in gridView2.GetSelectedRows())
            {
                juan.Add(juanList[j]);
            }
            return juan;
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            if (txtckmc.Text == "" || txtkehu.Text == "")
            {
                MessageBox.Show("请选择收货地址或者供货商！保存失败", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (gridView2.SelectedRowsCount == 0)
            {
                if (juanList.Count > 0)
                {
                    MessageBox.Show("没有任何卷被选中！保存失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
          
            //生成新单据
            InitDanju();
            try
            {
                using (var tran = Connect.dbcontext.UseTran ())
                {
                    ///////
                    if (useful == FormUseful.新增)
                    { ////检查库存。没有不能发货
                        /// if (useful == FormUseful.新增)
                        客供出仓单BLL.保存( danju, danjumingxitables.Where(x=>!string.IsNullOrEmpty( x.pingming)).ToList(),  CreatJuanhao() );
                    }
                    else
                    {
                         客供出仓单BLL.修改单据( danju,  danjumingxitables.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList(),  CreatJuanhao() );
                    }
                    tran.CommitTran();
                    AlterDlg.Show("保存成功！");
                    if (ShowMessageBox.ShowAskBox("是否继续新增操作？") == DialogResult.Yes)
                    {
                        Init();
                        gridControl2.DataSource = null;
                        gridView2.RefreshData();
                    }
                    else
                    {
                        MainForm.mainform.CloseTab();
                    }
                    //清空所有控件
                }
            }
            catch(Exception ex)
            {
                ShowMessageBox.ShowErrorBox(ex.Message);
            }
        }
        private void Init()
        { 
            foreach (Control  c in this.groupPanel2 .Controls  )
            {
                if(c is DevComponents.DotNetBar.Controls.TextBoxX)
                {
                    c.Text = "";
                }
                if(c is DevExpress.XtraEditors.ButtonEdit)
                {
                    c.Text = "";
                }
            }
            dateEdit1.DateTime = DateTime.Now.Date;
            txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.客供出仓单, dateEdit1.DateTime, DanjuLeiXing.客供出仓单 );
            danjumingxitables = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == txtdanhao.Text);
            var length = danjumingxitables.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                danjumingxitables.Add(new danjumingxitable() { danhao = txtdanhao.Text,rq=dateEdit1.DateTime  });
            }
            gridControl1.DataSource = danjumingxitables;
            gridControl1.RefreshDataSource();
            juanList.Clear();
            gridControl2.RefreshDataSource();
            txtckmc.Text = QueryTime.DefaultStock;
            cmb领用人.Text = string.Empty;
            useful = FormUseful.新增;
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView2) { formname = this.Name, Obj = new JuanHaoTable () };
            fm.ShowDialog();
        }

        private void gridView2_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            new StockHelper() { DetailgridControl = gridControl1, MinxiGridview = gridView1, danjumingxitables = danjumingxitables, juanList = juanList }.SelectionChange(gridView2);
        }

        private void 客供出仓单_Load(object sender, EventArgs e)
        {
            if (useful == FormUseful.新增)
            {
                Init();
            }
            else
            {
                if (useful == FormUseful.修改)
                {
                    Edit();
                }
                else
                {
                    if (useful == FormUseful.查看)
                    {
                        Edit();
                        保存ToolStripMenuItem.Enabled = false;
                    }
                    else
                    {
                       
                    }
                }
            }
            danjumingxitables = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danju.dh);
            var length = danjumingxitables.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                danjumingxitables.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = dateEdit1.DateTime });
            }
            gridControl1.DataSource = danjumingxitables;
            if (useful == FormUseful.跳转)
            {
                CreateDanjuWithDanjumingxi();
                useful = FormUseful.新增;
            }
        }
        /// <summary>
        /// 根据单据明细生成单据
        /// </summary>
        private void CreateDanjuWithDanjumingxi()
        {
            txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.客供出仓单, dateEdit1.DateTime, DanjuLeiXing.客供出仓单);
            dateEdit1.DateTime = DateTime.Now.Date;
            danjumingxitables.ForEach(x => x.danhao = txtdanhao.Text);
            //初始化单据信息
            if (stockTables.Count > 0)
            {
                txtckmc.Text = stockTables[0].CKMC;
                txtkehu.Text = stockTables[0].CustomName;
                var lxr = LXRService.GetOneLXR(x => x.MC == txtkehu.Text);
                if (lxr != null)
                {
                  
                    danju.ksbh = lxr.BH;
                    danju.ksmc = lxr.MC;
                }
            }
            StockToDanjumingxi(stockTables);//生成单据明细
            加载卷();
            //把所有的细码都打上勾
            SetAllSelect();
        }
        /// <summary>
        /// 把所有的细码全部选中
        /// </summary>
        private void SetAllSelect()
        {
            for (int rowindex = 0; rowindex < gridView2.RowCount; rowindex++)
            {
                gridView2.SelectRow(rowindex);
            }
        }
        private void StockToDanjumingxi(List<StockTable> stocks)
        {
            SelectHelper.StockConverToDanjumingxi(gridView1, stocks, danjumingxitables, txtdanhao.Text, dateEdit1.DateTime, DanjuLeiXing.销售出库单);
            //自动填写价格();

            gridControl1.DataSource = danjumingxitables;
            gridControl1.RefreshDataSource();
            gridView1.CloseEditor();
            txtbeizhu.Text = danjumingxitables[0].houzhengli;
        }
        private void Edit()
        {
            txtdanhao.Text = danju.dh;
            txtbeizhu.Text = danju.bz;
            txtckmc.Text = danju.shouhuodizhi;
            cmbcunfang.Text = danju.ckmc;
            txtkehu.Text = danju.ksmc;
            dateEdit1.Text = danju.rq.ToShortDateString();
            cmb领用人.Text = danju.SaleMan;
            juanList = FahuoDanService.QueryJuanhaotableFromShipments(FahuoDanService.GetFahuoDanlst(x=>x.dh==danju.dh)).OrderBy (x=>x.GangHao ).ToList ();
            gridControl2.DataSource = juanList;
        }

        private void 码单预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintMadan(PrintModel.Privew );
        }

        private void 码单编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (后整理管理系统.自定义类.PrintService.CheckPrintDesignAccess())
            {
                PrintMadan(PrintModel.Design);
            }
        }

        private void 直接打印ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            PrintMadan(PrintModel.Print);
        }
        private void PrintMadan(PrintModel printsytle)
        {
            if (StockHelper.CheckMashu(CreatJuanhao()))
            {
                Tools.ShowMessageBox.ShowErrorBox("单据存在两种不同的挂码！不能打印单据！");
                return;
            }
            if (StockHelper.CheckDanWei(CreatJuanhao()))
            {
                Tools.ShowMessageBox.ShowErrorBox("单据存在两种不同的卷单位！不能打印单据！");
                return;
            }
            if (string.IsNullOrEmpty(txtkehu.Text))
            {
                Tools.ShowMessageBox.ShowErrorBox("客户名称缺失！不能打印单据");
                return;
            }
            InitDanju();
            var Yidabaolist = CreatJuanhao();
            try
            {

                switch (cmbMadanYangshi.Text)
                {
                    case "竖版样式":
                        new Tools.打印成品码单()
                        {
                            danjuTable = danju,
                            danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                            danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = gridView1.Name },
                            juanHaoTables = CreatJuanhao(),
                            mingxiinfo = new Tools.FormInfo() { FormName = "销售发货单", GridviewName = gridView1.Name }
                        }.Print(PrintPath.报表模板 + "\\madan.frx", printsytle);
                        break;
                    case "清单码单":
                        new Tools.打印清单码单()
                        {
                            danjuTable = danju,
                            danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                            danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = gridView1.Name },
                            juanHaoTables = CreatJuanhao(),
                            mingxiinfo = new Tools.FormInfo() { FormName = "销售发货单", GridviewName = gridView1.Name },
                            JuanInfo = new Tools.FormInfo { FormName = "打卷报表", GridviewName = gridView2.Name }
                        }.Print(PrintPath.报表模板 + "\\清单码单.frx", printsytle);
                        break;
                    case "横版样式":
                        if (Yidabaolist.Count > 0)
                        {
                            new Tools.打印横版码单()
                            {
                                danju = danju,
                                juanhaolist = Yidabaolist,
                                formInfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = "gridView1" },
                                danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                                mingxiinfo = new Tools.FormInfo() { FormName = "销售发货单", GridviewName = gridView1.Name }
                            }.打印(printsytle, PrintPath.报表模板 + "\\A4纸.frx");
                        }
                        else
                        {
                            MessageBox.Show("没有任何包装信息！打印失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        break;
                    case "横版款号":
                        if (Yidabaolist.Count > 0)
                        {
                            new Tools.打印横版码单()
                            {
                                danju = danju,
                                juanhaolist = Yidabaolist,
                                formInfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = "gridView1" },
                                danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                                mingxiinfo = new Tools.FormInfo() { FormName = "销售发货单", GridviewName = gridView1.Name }
                            }.打印(printsytle, PrintPath.报表模板 + "\\横版款号.frx");
                        }
                        else
                        {
                            MessageBox.Show("没有任何包装信息！打印失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;
                    case "包装样式":
                        if (Yidabaolist.Count > 0)
                        {
                            new Tools.打印包装码单() { danju = danju, juanhaolist = Yidabaolist, formInfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = "gridView1" } }.打印(printsytle, PrintPath.报表模板 + "\\打包码单.frx");
                        }
                        else
                        {
                            MessageBox.Show("没有任何包装信息！打印失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;
                }
                if (useful != FormUseful.查看)
                {
                    if (Tools.ShowMessageBox.ShowAskBox("是否直接保存单据？") == DialogResult.Yes)
                    {
                        保存ToolStripMenuItem_Click(null, null);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtkehu_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter )
            {
                var fm = new 客户选择() { linkman = new LXR() { ZJC = txtkehu.Text, MC = "" } };
                fm.ShowDialog();
                danju.ksbh = fm.linkman.BH;
                danju.ksmc = fm.linkman.MC;
                txtkehu.Text = danju.ksmc;
            }
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }

        private void 客供出仓单_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (txtkehu.Text != string.Empty)
            {
               e.Cancel  =! Sunny.UI.UIMessageBox.ShowAsk  ("您确定要关闭该页面吗？确定关闭按确定。否则按取消");
            }
        }

       

        private void 重新加载卷ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            重新加载卷();
        }
        private void 重新加载卷()
        {
            juanList.Clear();
            foreach (var d in danjumingxitables.Where(x => x.Bianhao != null))
            {
                juanList.AddRange(JuanHaoTableService.GetJuanHaoTablelst(x => x.ReceiptNo == d.rkdh && x.CustomerName == d.CustomName && x.yanse == d.yanse && x.GangHao == d.ganghao && x.Ckmc == txtckmc.Text ));
            }
            gridControl2.DataSource = juanList;
            gridControl2.RefreshDataSource();
        }

        private void 打印预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintAzhijia(PrintModel.Privew);
        }
        private void PrintAzhijia(PrintModel useful)
        {
            InitDanju();
            new Tools.打印发货单()
            {
                danjuTable = danju,
                danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = gridView1.Name },
                mingxiinfo = new Tools.FormInfo() { FormName = "销售发货单" , GridviewName = gridView1.Name }
            }.Print( PrintPath.报表模板 + "发货单.frx" ,useful);
          

            if (Sunny.UI.UIMessageBox.ShowAsk("该单据已打印！是否立即保存该单据"))
            {
                保存ToolStripMenuItem_Click(null, null);
            }
        }

        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintAzhijia(PrintModel.Design);
        }

        private void 直接打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintAzhijia(PrintModel.Print);
        }
    }
}
